package com.juzi.wopu.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.juzi.wopu.domain.Department;
import com.juzi.wopu.query.DepartmentQuery;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.service.IDepartmentService;

public class DepartmentAction extends CRUDAaction<Department>{
	
	private static final long serialVersionUID = 1L;

	private IDepartmentService departmentService;
	
	private Department department=new Department();
	//  实例化一个查询对象
	private DepartmentQuery baseQuery=new DepartmentQuery();
    // 当前类对象 是栈顶对象
	private PageList pageList;
	
	//private String companyName;
	
	public void setDepartmentService(IDepartmentService departmentService) {
		this.departmentService = departmentService;
	}
	
	//列表
	@Override
	protected void list() {
		this.pageList=departmentService.findByQuery(baseQuery);
		putContext("allDepts", departmentService.getAll());
	}
	
	@Override
	public String input() throws Exception{
		if(id!=null){
			department=departmentService.get(id);
		}
		return INPUT;
	}
	
	// 处理保存和修改方法
	@Override
	public String save() throws Exception {
		System.out.println(id);
		if(id==null){
			// 保存后添加到最后一页
			baseQuery.setCurrentPage(Integer.MAX_VALUE);
			department.setId(3L);
		}
		System.err.println("c cccccccccccccccccccccccc"+department);
		departmentService.save(department);
		return RELOAD;
	}

	// 删除
	@Override
	public String delete() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			if (id != null) {
				departmentService.delete(id);
				out.print("{\"success\":true,\"msg\":\"删除成功\"}");
			}else{
				out.print("{\"success\":false,\"msg\":\"没有删除成功\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"success\":false,\"msg\":\"异常信息:"+e.getMessage()+"\"}");
		}
		return null;
	}

	// input前置方法
	@Override
	public void prepareInput() throws Exception {
		if(id!=null){// 最主要做回显
			department=departmentService.get(id);// 变成栈顶对象
		}
	}

	// save前置方法
	@Override
	public void prepareSave() throws Exception {
		if(id!=null){
			// 修改后保存，保证修改后数据不会丢失
			department=departmentService.get(id);
		}else{
			//新增后的保存
			department=new Department();
		}
	}

	// 圧栈后院获取
	@Override
	public Department getModel() {
		return department;
	}
	
	public PageList getPageList() {
		return pageList;
	}


	public DepartmentQuery getBaseQuery() {
		return baseQuery;
	}


	public void setBaseQuery(DepartmentQuery baseQuery) {
		this.baseQuery = baseQuery;
	}
}
